import time
import threading
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy import (
    Column,
    Integer,
    String,
    DateTime)
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


from sitebase.config import config

engine = create_engine(
    "mysql+pymysql://%(DB_USER)s:%(DB_PASS)s@%(DB_SVR)s:%(DB_PORT)s/%(DB_NAME)s?charset=utf8"
    % config, echo=False, pool_recycle=7200)


class Person(Base):
    __tablename__ = 'person'

    id = Column(Integer, primary_key=True, autoincrement=True)
    firstname = Column(String(255), nullable=False)
    lastname = Column(String(255), nullable=False)

    def __str__(self):
        return "id: {0}, firstname: {1}, lastname: {2}".format(self.id, self.firstname, self.lastname)


"""
session_factory每实例化一次，都创建一个新对象。
Session在同一线程中无论实例化多少次，返回的都是同一对象；在不同线程中实例化后返回不同的对象。
"""
session_factory = sessionmaker(bind=engine)
Session = scoped_session(session_factory)


def get_scoped_session():
    """
    scoped_session
    :return:
    """
    return Session()


def get_session_no_scope():
    """ noscoped_session """
    return session_factory()


def job(name):
    session = get_scoped_session()
    # session = get_session_no_scope()
    # 这里打印一下 session id  
    print(f"naem:{name}, id session:{id(session)}")
    session.baohua = 333

    # person = Person(firstname='frank-' + name, lastname='111111')
    # print(f"{name} person is add..")
    # session.add(person)

    time.sleep(2)

    session = get_scoped_session()
    print(f"naem:{name}, id session:{id(session)}")
    print(session.baohua)
    # if name == 'job3':
    #     # 线程3 提交 , 其他线程不提交.
    #     session.commit()


if __name__ == '__main__':

    thread_list = []

    # 创建5个线程
    for i in range(5):
        name = 'job' + str(i)
        t = threading.Thread(target=job, name=name, args=(name,))

        thread_list.append(t)

    for t in thread_list:
        t.start()

    for t in thread_list:
        t.join()